﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Async_Fibonaci
{
    public partial class CalculateFibonacciForm : Form
    {
        public CalculateFibonacciForm()
        {
            InitializeComponent();
        }

        private async void calculateButton_Click(object sender, EventArgs e)
        {
            outputTextBox.Text = string.Empty;
            timeLabel.Text = string.Empty;

            outputTextBox.Text = "Calculating...";            

            try
            {
                DateTime startTime = DateTime.Now;
                long result = await Task<long>.Run(() => Fibonaci(Convert.ToInt64(inputTextBox.Text)));
                DateTime endTime = DateTime.Now;

                timeLabel.Text = string.Format("{0:F3} seconds", endTime.Subtract(startTime).TotalSeconds);
                outputTextBox.Text = result.ToString();

            }
            catch (FormatException ex)
            {
                outputTextBox.Text = string.Empty;
                MessageBox.Show(ex.Message, "Invalid Argument", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);                
            }            

        }

        private long Fibonaci(long n)
        {
            if (n == 1 || n == 0)
                return 1;
            else
            {
                return Fibonaci(n - 1) + Fibonaci(n - 2);
            }
        }
    }
}
